﻿using System;
using System.Drawing;
using System.Linq;
using System.Web.Security;
using System.Web.UI.WebControls;
using FranceTriple.Dal;

namespace TeamFranceTriple
{
    public partial class AwaitingUsers : BaseUserControl
    {
        private static Color RedColor = Color.FromArgb(
                        Convert.ToInt32("44", 16),
                        Convert.ToInt32("00", 16),
                        Convert.ToInt32("00", 16));

        private static Color GreenColor = Color.FromArgb(
                Convert.ToInt32("00", 16),
                Convert.ToInt32("a1", 16),
                Convert.ToInt32("00", 16));

        private String selectedUsername = String.Empty;

        protected void Page_PreRender(object sender, EventArgs e)
        {
            var query = (from awu in ForumInfo.AwaitingUsers
                         orderby awu.UserName
                         select new
                         {
                             awu.ProviderUserKey,
                             awu.UserName,
                             awu.Email,
                             awu.CreationDate,
                             awu.LastLoginDate,
                             awu.LastActivityDate,
                             awu.LastLockoutDate,
                             awu.LastPasswordChangedDate,
                             awu.IsApproved,
                             awu.IsLockedOut,
                             NbRoleOwned = Roles.GetRolesForUser(awu.UserName).Count()
                         });
            AwaitingUserGridView.DataSource = query;
            AwaitingUserGridView.DataBind();
        }


        protected void AwaitingUserGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            var IsAdminHr = ThisMaster.Requester.Roles.Contains("RoleHR");

            if (e.Row.RowIndex > -1)
            {
                var buttonEmailSend = e.Row.Cells[3].Controls[0] as Button;
                buttonEmailSend.Enabled = false;

                var buttonRoles = e.Row.Cells[13].Controls[0] as Button;


                var buttonProfile = e.Row.Cells[14].Controls[0] as Button;
                buttonProfile.Enabled = false;

                var buttonPrivateMessage = e.Row.Cells[15].Controls[0] as Button;
                buttonPrivateMessage.Enabled = false;

                var buttonResetPassword = e.Row.Cells[16].Controls[0] as Button;
                buttonResetPassword.Enabled = false;

                var buttonUserDelete = e.Row.Cells[17].Controls[0] as Button;
                buttonUserDelete.Enabled = false;

                var IsApprovedCell = e.Row.Cells[7];
                var IsApproved = e.Row.Cells[7].Controls[0] as CheckBox;
                if (IsApproved != null && !IsApproved.Checked)
                    IsApprovedCell.BackColor = RedColor;

                var buttonActivationEmailSend = e.Row.Cells[8].Controls[0] as Button;
                buttonActivationEmailSend.Enabled = IsAdminHr && !IsApproved.Checked;

                var buttonUserActivate = e.Row.Cells[9].Controls[0] as Button;
                if (IsApproved.Checked)
                {
                    buttonUserActivate.Enabled = IsAdminHr;
                    buttonUserActivate.CommandName = "UserDesactivate";
                    buttonUserActivate.Text = "UserDesactivate".ToLocalizedString();
                }
                else
                {
                    buttonUserActivate.Enabled = IsAdminHr;
                    buttonUserActivate.CommandName = "UserActivate";
                    buttonUserActivate.Text = "UserActivate".ToLocalizedString();
                }

                var IsLockedOutCell = e.Row.Cells[10];
                var IsLockedOut = e.Row.Cells[10].Controls[0] as CheckBox;
                if (IsLockedOut != null && IsLockedOut.Checked)
                    IsLockedOutCell.BackColor = RedColor;

                var buttonUnlockUser = e.Row.Cells[11].Controls[0] as Button;
                buttonUnlockUser.Enabled = IsAdminHr && IsLockedOut.Checked;

                var NbRoleOwnedCell = e.Row.Cells[12];

                var NbRoleOwned = Int32.Parse(e.Row.Cells[12].Text);
                if (NbRoleOwned == 0)
                    NbRoleOwnedCell.BackColor = RedColor;
            }
        }

        protected void AwaitingUserGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            var rowIndex = Int32.Parse(e.CommandArgument.ToString());
            var username = AwaitingUserGridView.Rows[rowIndex].Cells[1].Text;
            var membershipuser = Membership.GetUser(username, false);

            UsernameLabel.Text = username;
            UsernameLabel.ForeColor = GreenColor;

            switch (e.CommandName)
            {
                case "EmailSend":
                    break;
                case "ActivationEmailSend":
                    membershipuser.Comment += membershipuser.ProviderUserKey.ToString();
                    Membership.UpdateUser(membershipuser);

                    switch (ThisMaster.Requester.Culture)
                    {
                        case "fr-fr":
                            new MailManager().SendActivationEmail(username, Server.MapPath("~/EmailTemplate/WelcomeNewUser.fr.htm"), true);
                            break;
                        default:
                            new MailManager().SendActivationEmail(username, Server.MapPath("~/EmailTemplate/WelcomeNewUser.en.htm"), true);
                            break;
                    }

                    break;
                case "UserActivate":
                    membershipuser.IsApproved = true;
                    membershipuser.Comment = membershipuser.Comment.Replace(membershipuser.ProviderUserKey.ToString(), "");
                    Membership.UpdateUser(membershipuser);
                    break;
                case "UserDesactivate":
                    membershipuser.IsApproved = false;
                    //Ne pas permettre de réactiver avec un email précédement conservé
                    membershipuser.Comment = membershipuser.Comment.Replace(membershipuser.ProviderUserKey.ToString(), "");
                    Membership.UpdateUser(membershipuser);
                    break;

                case "UnlockUser":
                    membershipuser.UnlockUser();
                    break;
                case "Roles":
                    selectedUsername = username;
                    UserIsInRoleListView.Visible = true;
                    UserIsInRoleListView.DataBind();
                    break;
                case "Profile":

                    break;
                case "PrivateMessage":

                    break;
                case "ResetPassword":

                    break;
                case "UserDelete":

                    break;

                default:
                    throw new ApplicationException("AwaitingUserGridView_RowCommand Not Implemented: " + e.CommandName.TextToHtml());
            }
        }

        protected void UserIsInRoleCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            Boolean addToRole = (sender as CheckBox).Checked;

            var rolename = ((sender as CheckBox).Parent.Controls[5] as Label).Text;

            if (addToRole)
            {
                if (!Roles.IsUserInRole(UsernameLabel.Text, rolename))
                    Roles.AddUserToRole(UsernameLabel.Text, rolename);
            }
            else
            {
                if (Roles.IsUserInRole(UsernameLabel.Text, rolename))
                    Roles.RemoveUserFromRole(UsernameLabel.Text, rolename);
            }

            AwaitingUserGridView.DataBind();
        }
        protected void UserIsInRoleListView_ItemDatabound(object sender, ListViewItemEventArgs e)
        {
            ListViewItem item = e.Item;
            aspnet_Role ThisRole = null;
            Label RoleNameLabel;
            CheckBox UserIsInRoleCheckBox;

            if (item.ItemType == ListViewItemType.DataItem)
            {
                ThisRole = item.DataItem as aspnet_Role;
                if (ThisRole != null)
                {
                    RoleNameLabel = item.FindControl("RoleNameLabel") as Label;
                    if (RoleNameLabel != null)
                    {
                        RoleNameLabel.Text = ThisRole.RoleName.ToLocalizedString();
                    }

                    UserIsInRoleCheckBox = item.FindControl("UserIsInRoleCheckBox") as CheckBox;
                    if (UserIsInRoleCheckBox != null)
                    {
                        UserIsInRoleCheckBox.Checked = Roles.IsUserInRole(selectedUsername, ThisRole.RoleName);
                    }
                }
            }
        }
    }
}
